package com.szj360.utils;

import java.util.Map;

import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ImageBase64Utils {
	public static UploadManager uploadManager = new UploadManager();
	 
    public static String GetImageStr(byte[] data) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
 
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
//    	return Base64.encodeToString(data,0);
    }
 
    public static String generateImage(String path, String imgStr) {//对字节数组字符串进行Base64解码并生成图片
//        System.out.println("imgStr == null:" + imgStr == null);
        if (imgStr == null) //图像数据为空
        {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
//            String imgFilePath = path;//新生成的图片
//            OutputStream out = new FileOutputStream(imgFilePath);
            Response r = uploadManager.put(b, path, QiniuUtils.getToken());
            String s = r.bodyString();
            if(s!=null&&!"".equals(s)){
            	Map m = JsonUtils.readJsonToMap(s);
            	if(m!=null){
            		return QiniuUtils.getPrefix() + "/" + m.get("key");
            	}
            }
            
//            out.write(b);
//            out.flush();
//            out.close();
            return null;
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
}